<template>
  <div v-if="showUpdateDialog">
    <n-modal v-model:show="showUpdateDialog" :mask-closable="false">
      <n-card
        style="
          width: 600px;
          background: #ffffff;
          border: 1px solid #e5e7eb;
          border-radius: 12px;
          box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        "
        title=""
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <template #header>
          <div style="color: #374151; font-size: 20px; font-weight: 600; text-align: center; padding: 8px 0;">
            <!-- 使用云下载图标，更符合更新场景 -->
            <n-icon size="24" style="margin-right: 8px; vertical-align: middle; color: #3b82f6;">
              <UpdateIcon />
            </n-icon>
            发现新版本
          </div>
        </template>

        <div style="padding: 10px;">
          <n-space vertical size="large">
            <div v-if="updateInfo" style="text-align: center;">

              <div
                style="
                  margin-top: 20px;
                  display: flex;
                  justify-content: space-between;
                  background: #f9fafb;
                  padding: 20px;
                  border-radius: 8px;
                  border: 1px solid #e5e7eb;
                "
              >
                <div style="text-align: center; flex: 1;">
                  <n-text
                    depth="3"
                    style="font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280;"
                    >当前版本
                  </n-text>
                  <n-text
                    strong
                    style="display: block; font-size: 16px; margin-top: 6px; color: #374151;"
                  >
                    {{ currentVersion }}
                  </n-text>
                </div>
                <div style="width: 1px; background: #d1d5db; margin: 0 20px;"></div>
                <div style="text-align: center; flex: 1;">
                  <n-text
                    depth="3"
                    style="font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280;"
                    >最新版本
                  </n-text>
                  <n-text
                    strong
                    style="display: block; font-size: 16px; margin-top: 6px; color: #059669;"
                  >
                    {{ updateInfo.tag_name }}
                  </n-text>
                </div>
              </div>

              <n-text depth="3" style="display: block; margin-top: 16px; font-size: 14px; color: #6b7280;">
                发布时间: {{ formatDate(updateInfo.created_at) }}
              </n-text>
            </div>

            <n-collapse v-if="updateInfo?.body" style="border-radius: 8px; border: 1px solid #e5e7eb;padding: 3px;">
              <n-collapse-item title="📋 更新说明" name="changelog" style="padding: 3px;">
                <div style="white-space: pre-wrap; line-height: 1.6; color: #374151; padding: 4px 0;">
                  {{ updateInfo.body }}
                </div>
              </n-collapse-item>
            </n-collapse>

            <div v-if="isUpdating" style="background: #f9fafb; padding: 20px; border-radius: 8px; border: 1px solid #e5e7eb;">
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin-bottom: 16px;
                "
              >
                <n-text strong style="color: #111827; font-size: 14px;">{{ updateStatus }}</n-text>
                <!-- 只有当总大小已知时才显示百分比 -->
                <n-text style="font-size: 14px; color: #6b7280;" v-if="totalBytes > 0">
                  {{ updateProgress.toFixed(1) }}%
                </n-text>
                <n-text style="font-size: 14px; color: #6b7280;" v-else>
                  {{ formatBytes(downloadedBytes) }}
                </n-text>
              </div>

              <n-progress
                type="line"
                :percentage="updateProgress"
                :show-indicator="false"
                :height="6"
                border-radius="3px"
                fill-border-radius="3px"
                style="margin-bottom: 16px;"
                :indeterminate="totalBytes === 0"
                color="#3b82f6"
              />

              <div
                v-if="downloadSpeed > 0"
                style="
                  display: flex;
                  justify-content: space-between;
                  font-size: 12px;
                  color: #6b7280;
                "
              >
                <span>下载速度: {{ formatSpeed(downloadSpeed) }}</span>
                <!-- 只有当总大小已知且预计时间大于0时才显示剩余时间 -->
                <span v-if="totalBytes > 0 && estimatedTime > 0"
                  >预计剩余: {{ formatTime(estimatedTime) }}</span
                >
              </div>
            </div>

            <n-alert
              v-if="!isUpdating"
              type="info"
              style="
                border-radius: 8px;
                border: 1px solid #dbeafe;
                background: #eff6ff;
              "
            >
              <template #icon>
              <!-- 使用提醒图标 -->
              <n-icon style="color: #3b82f6;">
                <AlertIcon />
              </n-icon>
              </template>
              <span style="color: #1e40af; font-weight: 500;"
                >更新完成后应用将自动重启，请保存当前工作。</span
              >
            </n-alert>
          </n-space>
        </div>

        <template #footer>
          <div
            style="
              background: #f9fafb;
              margin: 0;
              padding: 16px 24px;
              border-radius: 0 0 12px 12px;
              border-top: 1px solid #e5e7eb;
            "
          >
            <n-space justify="end" size="medium">
              <n-button
                @click="showUpdateDialog = false"
                :disabled="isUpdating"
                size="medium"
                style="
                  border-radius: 6px;
                  padding: 0 20px;
                  border: 1px solid #d1d5db;
                  color: #374151;
                "
              >
                稍后提醒
              </n-button>
              <n-button
                type="primary"
                @click="handleUpdate"
                :loading="isUpdating"
                size="medium"
                style="
                  border-radius: 6px;
                  padding: 0 20px;
                  background: #3b82f6;
                  border: 1px solid #3b82f6;
                "
              >
                <template #icon v-if="!isUpdating">
                  <!-- 使用云下载图标作为下载按钮图标 -->
                  <n-icon>
                    <UpdateIcon />
                  </n-icon>
                </template>
                {{ isUpdating ? '更新中...' : '立即更新' }}
              </n-button>
            </n-space>
          </div>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { invoke } from '@tauri-apps/api/core';
  import { getVersion } from '@tauri-apps/api/app';
  import { listen } from '@tauri-apps/api/event';
  import { 
    CloudDownload as UpdateIcon,     // 云下载图标，适合更新场景
    Refresh as RefreshIcon,          // 刷新图标
    Checkmark as SuccessIcon,        // 成功图标
    Alert as AlertIcon               // 提醒图标
  } from '@vicons/ionicons5';


  interface UpdateInfo {
    tag_name: string;
    name: string;
    body: string;
    created_at: string;
    assets: Array<{
      name: string;
      browser_download_url: string;
    }>;
  }

  interface DownloadProgress {
    downloaded: number;
    total: number;
    speed: number;
  }

  const message = useMessage();
  const showUpdateDialog = ref(false);
  const isUpdating = ref(false);
  const updateProgress = ref(0);
  const updateStatus = ref('');
  const updateInfo = ref<UpdateInfo | null>(null);
  const currentVersion = ref('');
  const downloadSpeed = ref(0);
  const estimatedTime = ref(0);
  const startTime = ref(0);
  const downloadedBytes = ref(0);
  const totalBytes = ref(0);

  let unlistenProgress: (() => void) | null = null;

  // 格式化下载速度
  const formatSpeed = (bytesPerSecond: number): string => {
    if (bytesPerSecond < 1024) {
      return `${bytesPerSecond.toFixed(0)} B/s`;
    } else if (bytesPerSecond < 1024 * 1024) {
      return `${(bytesPerSecond / 1024).toFixed(1)} KB/s`;
    } else {
      return `${(bytesPerSecond / (1024 * 1024)).toFixed(1)} MB/s`;
    }
  };

  // 格式化时间
  const formatTime = (seconds: number): string => {
    if (seconds < 60) {
      return `${seconds.toFixed(0)}秒`;
    } else if (seconds < 3600) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${minutes}分${remainingSeconds.toFixed(0)}秒`;
    } else {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      return `${hours}小时${minutes}分钟`;
    }
  };

  // 获取当前版本号
  const getCurrentVersion = async () => {
    try {
      currentVersion.value = await getVersion();
    } catch (error) {
      console.error('获取当前版本失败:', error);
      currentVersion.value = '未知';
    }
  };

  // 监听下载进度
  const setupProgressListener = async () => {
    try {
      unlistenProgress = await listen<DownloadProgress>('download-progress', (event) => {
        const progress = event.payload;
        downloadedBytes.value = progress.downloaded;
        totalBytes.value = progress.total;

        // 只有当总大小大于0时才计算百分比进度
        if (progress.total > 0) {
          updateProgress.value = (progress.downloaded / progress.total) * 100;
        } else {
          // 如果总大小未知，显示一个动态进度条
          updateProgress.value = Math.min(90, (progress.downloaded / (1024 * 1024)) * 10); // 每MB显示10%，最大90%
        }

        // 计算下载速度
        const currentTime = Date.now();
        const elapsedTime = (currentTime - startTime.value) / 1000; // 秒

        if (elapsedTime > 0) {
          downloadSpeed.value = progress.downloaded / elapsedTime;

          // 只有当总大小已知时才计算预计剩余时间
          if (progress.total > 0) {
            const remainingBytes = progress.total - progress.downloaded;
            if (downloadSpeed.value > 0) {
              estimatedTime.value = remainingBytes / downloadSpeed.value;
            }
          } else {
            estimatedTime.value = 0; // 总大小未知时不显示预计时间
          }
        }

        // 更新状态显示
        if (progress.total > 0) {
          updateStatus.value = `正在下载... ${formatSpeed(downloadSpeed.value)}`;
        } else {
          updateStatus.value = `正在下载... ${formatSpeed(downloadSpeed.value)} (${formatBytes(
            progress.downloaded
          )})`;
        }
      });
    } catch (error) {
      console.error('设置进度监听失败:', error);
    }
  };

  // 添加字节格式化函数
  const formatBytes = (bytes: number): string => {
    if (bytes < 1024) {
      return `${bytes} B`;
    } else if (bytes < 1024 * 1024) {
      return `${(bytes / 1024).toFixed(1)} KB`;
    } else {
      return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
    }
  };

  const checkForUpdates = async () => {
    try {
      const result = (await invoke('check_for_updates')) as UpdateInfo | null;
      if (result) {
        updateInfo.value = result;
        showUpdateDialog.value = true;
      }
    } catch (error) {
      console.error('检查更新失败:', error);
      message.error(`检查更新失败: ${error}`);
    }
  };

  const handleUpdate = async () => {
    if (!updateInfo.value) return;

    isUpdating.value = true;
    updateProgress.value = 0;
    downloadSpeed.value = 0;
    estimatedTime.value = 0;
    startTime.value = Date.now();

    try {
      // 设置进度监听
      await setupProgressListener();

      // 查找 .exe 文件
      const exeAsset = updateInfo.value.assets.find((asset) =>
        asset.name.toLowerCase().endsWith('.exe')
      );

      if (!exeAsset) {
        throw new Error('未找到可执行文件');
      }
      // 下载更新包
      updateStatus.value = '正在连接服务器...';

      const newExePath = (await invoke('download_update', {
        downloadUrl: exeAsset.browser_download_url,
      })) as string;

      // 准备应用更新
      updateStatus.value = '正在准备更新...';
      updateProgress.value = 95;

      await invoke('apply_update', {
        newExePath: newExePath,
      });

      updateProgress.value = 100;
      updateStatus.value = '更新完成，应用即将重启...';

      message.success('更新完成，应用即将重启');
    } catch (error) {
      message.error(`更新失败: ${error}`);
      updateStatus.value = `更新失败: ${error}`;
      isUpdating.value = false;
    }
  };

  const formatDate = (dateString: string) => {
    try {
      if (!dateString) return '未知';

      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return dateString;
      }

      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      });
    } catch (error) {
      console.error('日期格式化失败:', error);
      return dateString || '未知';
    }
  };

  // 定期检查更新（每4小时检查一次）
  const startPeriodicCheck = () => {
    setInterval(checkForUpdates, 4 * 60 * 60 * 1000);
  };

  onMounted(async () => {
    await getCurrentVersion();
    setTimeout(checkForUpdates, 5000);
    startPeriodicCheck();
  });

  onUnmounted(() => {
    if (unlistenProgress) {
      unlistenProgress();
    }
  });

  defineExpose({
    checkForUpdates,
  });
</script>

<style scoped>
  .n-progress :deep(.n-progress-graph-line-fill) {
    transition: all 0.3s ease;
    background: #3b82f6;
  }

  .n-card :deep(.n-card-header) {
    padding: 16px 24px;
    border-bottom: 1px solid #e5e7eb;
  }

  .n-button:hover {
    transform: translateY(-1px);
    transition: all 0.2s ease;
  }

  .n-collapse :deep(.n-collapse-item__header) {
    padding: 12px 16px;
    font-weight: 500;
    color: #374151;
  }

  .n-collapse :deep(.n-collapse-item__content-wrapper) {
    padding: 0 16px 16px 16px;
  }
</style>